#include "plotdialog.h"
#include "console.h"
#include "mainwindow.h"
#include "ui_plotdialog.h"

PlotDialog::PlotDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::PlotDialog)
{
    ui->setupUi(this);

    buffer_length = 1000;
    ui->lineEdit_BufferLen->setText("1000");

    ClearData();
}

PlotDialog::~PlotDialog()
{
    delete ui;
}

void PlotDialog::Copy2Buffer(const QByteArray &data)
{
    QByteArray dbuf = data;
    int offset = dbuf.size();

    // Data Shifting
    if ((point_cnt+offset)>=buffer_length) {
        for(int i=0; i<(buffer_length-offset); i++) {
            data_x[i] = data_x[i+(point_cnt+offset-buffer_length)];
        }
        for(int i=(buffer_length-offset); i<buffer_length; i++) {
            data_x[i] = dbuf[i-(buffer_length-offset)];
        }
    }else{
        for(int i=point_cnt; i<(point_cnt+offset); i++){
            data_x[i] = dbuf[i-point_cnt];
        }
        point_cnt += offset;
    }

    // copy to buffer
    for(int i=0; i<buffer_length; i++) {
        dbuf[i] = data_x[i];
    }

    Replot(ui->customPlot, dbuf);

}

void PlotDialog::getData(const QByteArray &data)
{
    Copy2Buffer(data);
}


void PlotDialog::Replot(QCustomPlot *customPlot, const QByteArray &data)
{
    QByteArray dbuf = data;
    QVector<double> vx(buffer_length), vy(buffer_length); // initialize
    for (int i=0; i<buffer_length; ++i)
    {
        vy[i] = dbuf[i]; // x goes from -1 to 1
        vx[i] = i; // let's plot a quadratic function
    }
    // create graph and assign data to it:
    customPlot->addGraph();
    customPlot->graph(0)->setData(vx, vy);
    // give the axes some labels:
    customPlot->xAxis->setLabel("x");
    customPlot->yAxis->setLabel("y");
    // set axes ranges, so we see all data:
    customPlot->xAxis->rescale(true);
    customPlot->yAxis->rescale(true);
    //customPlot->yAxis->setRange(0, 1);
    customPlot->replot();
}


void PlotDialog::ClearData()
{
    QByteArray dbuf;
    point_cnt = 0;

    for(int i=0; i<buffer_length; i++) {
        dbuf[i] = 0;
    }

    Replot(ui->customPlot, dbuf);
}

void PlotDialog::on_lineEdit_BufferLen_editingFinished()
{
    buffer_length = ui->lineEdit_BufferLen->text().toInt();
}
